<template>
  <div class="counter-management">
    <!-- 页面标题 -->
    <div class="page-header">
      <div class="title-container">
        <el-icon>
          <FolderOpened />
        </el-icon> 档口管理
      </div>
      <el-button type="primary" class="add-button" @click="openDrawer">
        <el-icon>
          <Plus />
        </el-icon> 新增档口
      </el-button>
    </div>

    <!-- 搜索区域 -->
    <div class="search-container">
      <el-form :inline="true" class="search-form">
        <el-form-item label="档口名称" style="width: 320px;">
          <el-input v-model="searchForm.keyword" placeholder="请输入档口名称" />
        </el-form-item>
        <el-form-item label="状态">
          <el-select v-model="searchForm.status" placeholder="全部" style="width: 320px;">
            <el-option label="全部" value="" />
            <el-option label="营业中" value="1" />
            <el-option label="暂停营业" value="0" />
            <el-option label="删除" value="2" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">查询</el-button>
        </el-form-item>
        <el-form-item>
          <el-button @click="resetSearch">重置</el-button>
        </el-form-item>
      </el-form>
    </div>

    <!-- 卡片列表 -->
    <div class="card-container">
      <el-row :gutter="20">
        <el-col v-for="(item, index) in counterlist" :key="item.id" :xs="24" :sm="12" :md="8" :lg="6" class="card-col">
          <div class="counter-card">
            <div class="card-header">
              <h3 class="card-title">{{ item.name }}</h3>
              <span :class="getStatusClass(item.status)">
                {{ getStatusText(item.status) }}
              </span>
            </div>
            <div class="card-body">
              <div class="info-item">
                <i class="el-icon-location" /> <el-icon>
                  <Clock />
                </el-icon>{{ item.business_hours }}
              </div>
              <div class="info-item">
                <i class="el-icon-user" /> <el-icon>
                  <UserFilled />
                </el-icon>{{ item.main_body }}
              </div>
              <div class="info-item">
                <i class="el-icon-phone" /> <el-icon>
                  <PhoneFilled />
                </el-icon>{{ formatPhoneNumber(item.contact_phone) }}
              </div>
            </div>
            <div class="card-footer">
              <el-button size="small" type="text" @click="openEditDrawer(item)">
                <el-icon>
                  <Edit />
                </el-icon>编辑
              </el-button>
              <el-button size="small" type="text" @click="openViewDrawer(item)">
                <el-icon>
                  <View />
                </el-icon>查看
              </el-button>
            </div>
          </div>
        </el-col>
      </el-row>
    </div>

    <!-- 分页 -->
    <div class="pagination-container">
      <el-pagination background layout="total, sizes, prev, pager, next, jumper" :current-page="currentPage"
        :page-sizes="[8, 16, 32, 64]" :page-size="pageSize" :total="total" @size-change="handleSizeChange"
        @current-change="handlePageChange" />
    </div>
  </div>

  <!-- 新增档口抽屉 -->
  <el-drawer v-model="drawerVisible" title="新增档口" size="32%" direction="rtl" :before-close="handleClose"
    @close="resetForm">
    <div class="drawer-content" style="position: relative;bottom: 40px;right: 5px;">
      <!-- 基本信息 -->
      <div class="section">
        <h3 class="section-title">基本信息</h3>
        <el-form :model="form" :rules="rules" ref="formRef" label-width="100px">
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="档口名称 " prop="name">
                <el-input v-model="form.name" placeholder="请输入档口名称" />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="位置" prop="position">
                <el-input v-model="form.position" placeholder="请输入档口位置" />
              </el-form-item>
            </el-col>
          </el-row>

          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="负责人" prop="main_body">
                <el-input v-model="form.main_body" placeholder="请输入负责人" />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="联系方式" prop="contact_phone">
                <el-input v-model="form.contact_phone" placeholder="请输入联系方式" />
              </el-form-item>
            </el-col>
          </el-row>

          <el-form-item label="状态" prop="status">
            <el-select v-model="form.status" placeholder="请选择状态">
              <el-option label="营业中" value="1" />
              <el-option label="暂停营业" value="0" />
              <el-option label="删除" value="2" />
            </el-select>
          </el-form-item>

          <el-form-item label="备注" prop="remark">
            <el-input v-model="form.remark" type="textarea" :rows="3" placeholder="请输入备注信息" />
          </el-form-item>
        </el-form>
      </div>

      <!-- 经营信息 -->
      <div class="section">
        <h3 class="section-title">经营信息</h3>
        <el-form :model="form" label-width="100px">
          <el-form-item label="营业时间" prop="businessHours">
            <el-input v-model="form.businessHours" placeholder="请输入营业时间" />
          </el-form-item>
        </el-form>
      </div>
    </div>

    <!-- 抽屉底部按钮 -->
    <template #footer>
      <div class="drawer-footer">
        <el-button @click="handleClose">取消</el-button>
        <el-button type="primary" @click="submitForm">保存</el-button>
      </div>
    </template>
  </el-drawer>

  <!-- 编辑档口抽屉 -->
  <el-drawer v-model="editDrawerVisible" title="编辑档口" size="32%" direction="rtl" :before-close="handleEditClose"
    @close="resetEditForm">
    <div class="edit-drawer-content" style="position: relative;bottom: 60px;right: 5px;">
      <!-- 基本信息 -->
      <div class="section">
        <h3 class="section-title">基本信息</h3>
        <el-form :model="editForm" :rules="editRules" ref="editFormRef" label-width="100px">
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="档口名称" prop="name">
                <el-input v-model="editForm.name" placeholder="请输入档口名称" />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="位置" prop="position">
                <el-input v-model="editForm.position" placeholder="请输入档口位置" />
              </el-form-item>
            </el-col>
          </el-row>

          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="负责人" prop="main_body">
                <el-input v-model="editForm.main_body" placeholder="请输入负责人" />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="联系方式" prop="contact_phone">
                <el-input v-model="editForm.contact_phone" placeholder="请输入联系方式" />
              </el-form-item>
            </el-col>
          </el-row>

          <el-form-item label="状态" prop="status">
            <el-select v-model="editForm.status" placeholder="请选择状态">
              <el-option label="营业中" value="1" />
              <el-option label="暂停营业" value="0" />
              <el-option label="删除" value="2" />
            </el-select>
          </el-form-item>

          <el-form-item label="备注" prop="notes">
            <el-input v-model="editForm.notes" type="textarea" :rows="3" placeholder="请输入备注信息" />
          </el-form-item>
        </el-form>
      </div>

      <!-- 经营信息 -->
      <div class="section">
        <h3 class="section-title">经营信息</h3>
        <el-form :model="editForm" label-width="100px">
          <el-form-item label="营业时间" prop="businessHours">
            <el-input v-model="editForm.business_hours" placeholder="请输入营业时间" />
          </el-form-item>
        </el-form>
      </div>
    </div>

    <!-- 编辑抽屉底部按钮 -->
    <template #footer>
      <div class="edit-drawer-footer">
        <el-button @click="handleEditClose">取消</el-button>
        <el-button type="primary" @click="submitEditForm">保存</el-button>
      </div>
    </template>
  </el-drawer>

  <!-- 查看档口抽屉 -->
  <el-drawer v-model="viewDrawerVisible" title="查看档口" size="32%" direction="rtl" @close="resetViewForm">
    <div class="view-drawer-content" style="position: relative;bottom: 60px;right: 5px;">
      <!-- 基本信息 -->
      <div class="section">
        <h3 class="section-title">基本信息</h3>
        <el-form :model="viewForm" label-width="100px" disabled>
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="档口名称" prop="name">
                <el-input v-model="viewForm.name" placeholder="请输入档口名称" />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="位置" prop="position">
                <el-input v-model="viewForm.position" placeholder="请输入档口位置" />
              </el-form-item>
            </el-col>
          </el-row>

          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="负责人" prop="main_body">
                <el-input v-model="viewForm.main_body" placeholder="请输入负责人" />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="联系方式" prop="contact_phone">
                <el-input v-model="viewForm.contact_phone" placeholder="请输入联系方式" />
              </el-form-item>
            </el-col>
          </el-row>

          <el-form-item label="状态" prop="status">
            <el-select v-model="viewForm.status" placeholder="请选择状态" disabled>
              <el-option label="营业中" value="1" />
              <el-option label="暂停营业" value="0" />
              <el-option label="删除" value="2" />
            </el-select>
          </el-form-item>

          <el-form-item label="备注" prop="notes">
            <el-input v-model="viewForm.notes" type="textarea" :rows="3" placeholder="请输入备注信息" />
          </el-form-item>
        </el-form>
      </div>

      <!-- 经营信息 -->
      <div class="section">
        <h3 class="section-title">经营信息</h3>
        <el-form :model="viewForm" label-width="100px" disabled>
          <el-form-item label="营业时间" prop="business_hours">
            <el-input v-model="viewForm.business_hours" placeholder="请输入营业时间" />
          </el-form-item>
        </el-form>
      </div>
    </div>

    <!-- 抽屉底部按钮 -->
    <template #footer>
      <div class="drawer-footer">
        <el-button @click="handleViewClose">取消</el-button>
        <el-button type="primary" @click="handleViewClose">保存</el-button>
      </div>
    </template>
  </el-drawer>
</template>

<script setup>
import { ref, reactive } from 'vue';
import { ElMessage, ElMessageBox } from 'element-plus';
import { getStsloglist, createStslog, updateStslog, getStslog } from '../../api/logs';

// 搜索表单
const searchForm = ref({
  keyword: '',
});

// 分页与列表变量
const currentPage = ref(1);
const pageSize = ref(8);
const total = ref(0);
const counterlist = ref([]);

// ========== 表单相关 ==========

// ------ 新增表单 ------
// 新增档口表单数据
const form = reactive({
  name: '',
  position: '',
  main_body: '',
  contact_phone: '',
  businessHours: '',
  remark: '',
  status: '1'
});

// 表单验证规则
const rules = {
  name: [{ required: true, message: '请输入档口名称', trigger: 'blur' }],
  main_body: [{ required: true, message: '请输入负责人', trigger: 'blur' }],
  contact_phone: [{ required: true, message: '请输入联系方式', trigger: 'blur' }],
  businessHours: [{ required: true, message: '请输入营业时间', trigger: 'blur' }],
  status: [{ required: true, message: '请选择状态', trigger: 'change' }]
};

// 表单引用
const formRef = ref(null);

// ------ 编辑表单 ------
// 编辑档口表单数据
const editForm = reactive({
  id: '',
  name: '',
  position: '',
  main_body: '',
  contact_phone: '',
  business_hours: '',
  notes: '',
  status: '1'
});

// 编辑表单验证规则
const editRules = {
  name: [{ required: true, message: '请输入档口名称', trigger: 'blur' }],
  main_body: [{ required: true, message: '请输入负责人', trigger: 'blur' }],
  contact_phone: [{ required: true, message: '请输入联系方式', trigger: 'blur' }],
  status: [{ required: true, message: '请选择状态', trigger: 'change' }],
  business_hours: [{ required: true, message: '请输入营业时间', trigger: 'blur' }]
};

// 编辑表单引用
const editFormRef = ref(null);


// ========== 抽屉状态 ==========
const drawerVisible = ref(false);
const editDrawerVisible = ref(false); // 新增编辑抽屉状态


// ========== 方法定义 ==========

// ------ 工具方法 ------
// 根据状态值获取状态文本
const getStatusText = (status) => {
  switch (status) {
    case 1:
      return '正常营业';
    case 0:
      return '暂停营业';
    case 2:
      return '删除';
    default:
      return '未知状态';
  }
};

// 根据状态值获取状态样式类
const getStatusClass = (status) => {
  switch (status) {
    case 1:
      return 'status-online';
    case 0:
      return 'status-temporary';
    case 2:
      return 'status-offline';
    default:
      return 'status-unknown';
  }
};

// 格式化手机号码显示
const formatPhoneNumber = (phone) => {
  if (!phone) return '';
  // 只显示前3位和后4位，中间用*代替
  if (phone.length >= 7) {
    return phone.substring(0, 3) + '****' + phone.substring(phone.length - 4);
  }
  // 如果手机号码长度不足7位，则直接返回原号码
  return phone;
};


// ------ 数据获取方法 ------
// 获取档口列表
const fetchCounterList = async () => {
  try {
    const params = {
      page: currentPage.value,
      pagesize: pageSize.value,
      name: searchForm.value.keyword,
      status: searchForm.value.status === '' ? undefined : searchForm.value.status
    };
    const res = await getStsloglist(params);
    console.log('API 响应:', res);

    if (!res || res.code !== 0) {
      console.error('接口返回异常或失败');
      return;
    }

    const { list, total: apiTotal } = res.data;

    if (!Array.isArray(list)) {
      counterlist.value = [];
      total.value = 0;
      return;
    }

    // counterlist.value = list.map(item => ({
    //   id: item.stall_id || item.id || Date.now() + Math.random(), // 防止 key 为空
    //   name: item.name || '',
    //   status: item.status === 1 ? 'online' : 'offline',
    //   location: item.main_body || '',
    //   manager: item.main_body || '',
    //   phone: item.contact_phone || ''
    // }));

    counterlist.value = res.data.list[0];

    total.value = apiTotal;

    console.log('最终 counterlist:', counterlist.value);
  } catch (error) {
    console.error('获取档口列表失败:', error);
  }
};


// ------ 搜索相关方法 ------
// 查询按钮事件
const handleSearch = () => {
  currentPage.value = 1; // 重置页码
  fetchCounterList();
};

// 重置按钮事件
const resetSearch = () => {
  // 清空搜索条件
  searchForm.value.keyword = '';
  searchForm.value.status = null;

  // 重置页码到第一页
  currentPage.value = 1;

  // 刷新列表
  fetchCounterList();
};


// ------ 分页相关方法 ------
// 分页尺寸变更
const handleSizeChange = (val) => {
  pageSize.value = val;
  fetchCounterList();
};

// 分页页码变更
const handlePageChange = (val) => {
  currentPage.value = val;
  fetchCounterList();
};

// ------ 新增抽屉相关 ------
// 打开新增抽屉
const openDrawer = () => {
  drawerVisible.value = true;
  resetForm();
};

// // 关闭新增抽屉
// const handleClose = () => {
//   ElMessageBox.confirm('确定要放弃当前修改吗？', '提示', {
//     confirmButtonText: '确定',
//     cancelButtonText: '取消',
//     type: 'warning'
//   }).then(() => {
//     drawerVisible.value = false;
//   }).catch(() => {
//     // 用户点击了取消，不关闭抽屉
//   });
// };

// 重置新增表单
const resetForm = () => {
  form.name = '';
  form.position = '';
  form.main_body = '';
  form.contact_phone = '';
  form.status = '1';
  form.remark = '';
  form.businessHours = '';
};

// 提交新增表单
const submitForm = () => {
  formRef.value.validate((valid) => {
    if (valid) {
      const payload = {
        name: form.name,
        position: form.position,
        main_body: form.main_body,
        contact_phone: form.contact_phone,
        business_hours: form.businessHours,
        notes: form.remark,
        status: form.status
      };

      createStslog(payload)
        .then(res => {
          if (res.code === 0) {
            ElMessage.success('档口添加成功！');
            drawerVisible.value = false;
            fetchCounterList(); // 刷新列表
          } else {
            ElMessage.error(res.msg || '添加失败');
          }
        })
        .catch(err => {
          ElMessage.error('网络错误，请重试');
          console.error(err);
        });
    } else {
      ElMessage.error('请填写完整信息！');
    }
  });
};

// ------ 编辑抽屉相关 ------
// 打开编辑抽屉
const update_id = ref(null);
const openEditDrawer = (item) => {
  // console.log(item.stall_id)
  update_id.value = item.stall_id;
  editDrawerVisible.value = true;
  // 赋值时严格匹配editForm的字段
  editForm.id = item.id; // 必须赋值id，用于接口的路径参数
  editForm.name = item.name;
  editForm.position = item.position || '';
  editForm.business_hours = item.business_hours;
  editForm.notes = item.notes || ''; // 备注可选，做容错
  editForm.status = String(item.status); // 确保状态值为字符串类型
  // 其他非接口必填字段（如contact_phone）可保留赋值，不影响提交
  editForm.main_body = item.main_body || '';
  editForm.contact_phone = item.contact_phone || '';

  // 保存原始数据用于比较
  Object.assign(originalEditForm, editForm);
};

const originalEditForm = reactive({
  id: '',
  name: '',
  position: '',
  main_body: '',
  contact_phone: '',
  business_hours: '',
  notes: '',
  status: '1'
});

// 关闭编辑抽屉
const handleEditClose = () => {
  // 检查表单是否被修改
  const isModified =
    editForm.name !== originalEditForm.name ||
    editForm.position !== originalEditForm.position ||
    editForm.business_hours !== originalEditForm.business_hours ||
    editForm.notes !== originalEditForm.notes ||
    editForm.status !== originalEditForm.status ||
    editForm.main_body !== originalEditForm.main_body ||
    editForm.contact_phone !== originalEditForm.contact_phone;

  if (isModified) {
    ElMessageBox.confirm('确定要放弃当前修改吗？', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }).then(() => {
      editDrawerVisible.value = false;
      // 重置表单为原始值
      Object.assign(editForm, originalEditForm);
    }).catch(() => {
      // 用户点击了取消，不关闭抽屉
    });
  } else {
    editDrawerVisible.value = false;
  }
};

// 重置编辑表单
const resetEditForm = () => {
  editForm.id = '';
  editForm.name = '';
  editForm.position = '';
  editForm.main_body = '';
  editForm.contact_phone = '';
  editForm.status = '1';
  editForm.remark = '';
  editForm.businessHours = '';
};

// 提交编辑表单
const submitEditForm = () => {
  editFormRef.value.validate((valid) => {
    if (valid) {
      const formData = new FormData();
      // 严格匹配接口的参数
      formData.append('name', editForm.name);
      formData.append('position', editForm.position);
      formData.append('business_hours', editForm.business_hours);
      formData.append('notes', editForm.notes);
      formData.append('contact_phone', editForm.contact_phone);
      formData.append('main_body', editForm.main_body);
      formData.append('status', editForm.status);
      // 调用编辑接口，传入id和formData
      updateStslog(update_id.value, formData)
        .then((res) => {
          if (res.code === 0) {
            ElMessage.success('档口更新成功！');
            editDrawerVisible.value = false;
            fetchCounterList(); // 刷新列表
          } else {
            ElMessage.error(res.msg || '更新失败');
          }
        })
        .catch((err) => {
          ElMessage.error('网络错误，请重试');
          console.error(err);
        });
    } else {
      ElMessage.error('请填写完整信息！');
    }
  });
};

// ========== 查看抽屉相关 ==========
const viewDrawerVisible = ref(false);
const viewForm = reactive({
  id: '',
  name: '',
  position: '',
  main_body: '',
  contact_phone: '',
  business_hours: '',
  notes: '',
  status: '1'
});

// 打开查看抽屉
const openViewDrawer = async (item) => {
  try {
    const res = await getStslog(item.stall_id); // 调用 API 获取详情
    if (res.code === 0 && res.data) {
      const data = res.data;
      viewForm.stall_id = data.stall_id;
      viewForm.name = data.name;
      viewForm.position = data.position || '';
      viewForm.main_body = data.main_body || '';
      viewForm.contact_phone = data.contact_phone || '';
      viewForm.business_hours = data.business_hours || '';
      viewForm.notes = data.notes || '';
      viewForm.status = String(data.status); // 确保状态值为字符串类型
    } else {
      ElMessage.error('获取档口信息失败');
    }
  } catch (error) {
    ElMessage.error('网络错误，请重试');
  }
  viewDrawerVisible.value = true;
};

// 关闭查看抽屉
const handleViewClose = () => {
  viewDrawerVisible.value = false;
};

// 重置查看表单
const resetViewForm = () => {
  viewForm.id = '';
  viewForm.name = '';
  viewForm.position = '';
  viewForm.main_body = '';
  viewForm.contact_phone = '';
  viewForm.business_hours = '';
  viewForm.notes = '';
  viewForm.status = '1';
};



// 初始化加载列表
fetchCounterList();
</script>

<style scoped>
.counter-management {
  background-color: white;
  height: 100%;
  padding: 20px;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
  padding-bottom: 10px;
  border-bottom: 1px solid #e4e7ed;
}

.title-container {
  display: flex;
  align-items: center;
  font-size: 18px;
  font-weight: 600;
  color: #303133;
}

.add-button {
  padding: 8px 16px;
  font-size: 14px;
  border-radius: 4px;
}

.search-container {
  background: white;
  padding: 15px;
  border-radius: 8px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
  margin-bottom: 20px;
}

.search-form {
  margin: 0;
}

.card-container {
  margin-bottom: 20px;
}

.card-col {
  margin-bottom: 20px;
}

.counter-card {
  border: 1px solid #e4e7ed;
  border-radius: 8px;
  overflow: hidden;
  transition: all 0.3s ease;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
  height: 100%;
  display: flex;
  flex-direction: column;
}

.counter-card:hover {
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.15);
}

.card-header {
  padding: 15px;
  background-color: #fff;
  border-bottom: 1px solid #e4e7ed;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.card-title {
  font-size: 16px;
  font-weight: 600;
  color: #303133;
  margin: 0;
}

.status-online {
  padding: 2px 8px;
  border-radius: 4px;
  background-color: #e6f7ff;
  color: #1890ff;
  font-size: 12px;
}

.status-offline {
  padding: 2px 8px;
  border-radius: 4px;
  background-color: #fff1e6;
  color: #f56c6c;
  font-size: 12px;
}

.card-body {
  padding: 15px;
  background-color: #fff;
  flex: 1;
}

.info-item {
  display: flex;
  align-items: center;
  margin-bottom: 8px;
  font-size: 14px;
  color: #606266;
}

.info-item i {
  margin-right: 5px;
  color: #909399;
}

.card-footer {
  padding: 10px 15px;
  background-color: #f5f7fa;
  border-top: 1px solid #e4e7ed;
  display: flex;
  gap: 10px;
}

.card-footer .el-button {
  padding: 5px 10px;
  font-size: 12px;
}

.pagination-container {
  display: flex;
  justify-content: flex-end;
  margin-top: 10px;
}

.pagination-container .el-pagination {
  margin: 0;
}

/* 响应式调整 */
@media (max-width: 768px) {
  .card-col {
    margin-bottom: 15px;
  }

  .pagination-container {
    justify-content: center;
  }
}

/* 编辑抽屉样式 */
.edit-drawer-content {
  padding: 20px;
}

.section {
  margin-bottom: 20px;
}

.section-title {
  font-size: 16px;
  font-weight: 600;
  color: #303133;
  margin-bottom: 15px;
  border-bottom: 1px solid #e4e7ed;
  padding-bottom: 8px;
}

.edit-drawer-footer {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
  margin-top: 20px;
}

/* 查看抽屉样式 */
.view-drawer-content {
  padding: 20px;
}

.section {
  margin-bottom: 20px;
}

.section-title {
  font-size: 16px;
  font-weight: 600;
  color: #303133;
  margin-bottom: 15px;
  border-bottom: 1px solid #e4e7ed;
  padding-bottom: 8px;
}

.drawer-footer {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
  margin-top: 20px;
}
</style>